<template>
    <div class="app-container">
      <div class="task-panel">
        <div class="task-tool-row">
          <n-space>
            <n-select style="width: 220px" v-model:value="taskPanelStatus" :options="taskPanelOptions" />
            <n-select style="width: 220px" v-model:value="taskCategorySelector" :options="categoryOptions" placeholder="请选择任务分类" />
            <n-date-picker v-model:value="taskTimestamp" type="date" />
            <n-button type="info" @click="getSearchList">Search</n-button>
            <n-button type="primary" @click="refreshList">Refresh</n-button>
            <n-button @click="activate">Add</n-button>
            <n-button type="primary" @click="generateDailyLog">DailyLog</n-button>
          </n-space>
        </div>
        <n-data-table :loading="listLoading" :bordered="false" :single-line="false" :columns="columns" :data="taskList">
          <template #empty>
            <div>
              <n-space vertical>
                <img src="/relax.svg" alt="" style="width: 500px;">
                <span style="padding-top: 30px;font-size: 16px;font-weight:bold;color: #999;">Enjoy self with the clear list.</span>
              </n-space>
            </div>
          </template>
        </n-data-table>
        <div class="pagination" style="padding: 15px 0;display: flex;justify-content: flex-end;" v-if="taskList.length > 0">
          <n-pagination v-model:page="page" :page-count="pagination.pageCount" />
        </div>
      </div>


      <n-drawer v-model:show="active" :width="'50%'" placement="right">
        <n-drawer-content title="记录任务">
          <n-space vertical>
            <n-input v-model:value="newTask" placeholder="添加新任务" type="textarea" size="small" :autosize="{
              minRows: 3,
              maxRows: 5,
            }" />
            <n-select v-model:value="taskCategory" :options="categoryOptions" placeholder="请选择任务分类" />
            <n-checkbox v-model:checked="isUrgent">
              {{isUrgent?'加急':'不加急'}}
            </n-checkbox>
            <n-button type="primary" @click="submitTask">确认</n-button>
          </n-space>
        </n-drawer-content>
      </n-drawer>

      <n-modal
        v-model:show="rowModal.show"
        class="custom-card"
        preset="card"
        :style="{width: '650px',height: '500px'}"
        title="Task Info."
        size="large"
        bordered
        :segmented="{
          content: true,
          footer: true,
        }"
      >
          <ul>
            <li><span class="label_tk">Target:</span><span class="cnt" style="font-weight: bold;color:blueviolet;">{{ rowModal.row.content }}</span></li>
            <li><span class="label_tk">Status:</span><span class="cnt">{{ Number(rowModal.row.status)?'已完成':'未完成' }}</span></li>
            <li><span class="label_tk">Ember:</span><span class="cnt" :class="{'emmer':Number(rowModal.row.zhiding)}">{{ Number(rowModal.row.zhiding)?'紧急':'非紧急' }}</span></li>
            <li><span class="label_tk">LastUpdate:</span><span class="cnt">{{ rowModal.row.update_time }}</span></li>
            <li><span class="label_tk">Create:</span><span class="cnt">{{ rowModal.row.create_time }}</span></li>
          </ul>
        <template #footer>
        </template>
      </n-modal>
    </div>
</template>
<script setup>
import {h, onMounted, reactive, ref, watch} from 'vue';
import axios from 'axios';
import {NButton, NModal, NSelect, NTag, useMessage, useDialog} from 'naive-ui'
import {taskAddApiUrl, taskCategoryUrl, taskListApiUrl, taskUpdateApiUrl} from '../api.config.js';

const message = useMessage()
const dialog = useDialog()

const rowModal = reactive({
  row: null,
  show: false
});

const taskPanelStatus = ref(2);
const taskCategorySelector = ref()
const taskTimestamp = ref()

const categoryOptions = ref([])
const taskList = ref([])
const listLoading = ref(false);
const pagination = reactive({
  pageSize: 10,
  pageCount: 1,
  itemCount: 0,
})
const page = ref(1);
const active = ref(false)
const activeRow = ref()
const activate = (row) => {
  active.value = true
  activeRow.value = row
  newTask.value = activeRow.value.content
  taskCategory.value = activeRow.value.categoryId
  isUrgent.value = activeRow.value.zhiding == '1'
}

const taskCategory = ref();
const newTask = ref("");
const isUrgent = ref(false)
const submitTask = async () => {
  const task = newTask.value?.trim();
  if(!task)return;
  let data = {task}
  if(taskCategory.value){
    data = {
      category: taskCategory.value,
      zhiding: isUrgent.value,
      ...data,
    }
  }
  let result
  if(activeRow.value){
    data['id'] = activeRow.value.id
    result = await axios.post(taskUpdateApiUrl,data, { headers: {"Content-Type": "application/x-www-form-urlencoded"} })
  }else{
    result = await axios.post(taskAddApiUrl,data, { headers: {"Content-Type": "application/x-www-form-urlencoded"} })
  }
  if(result.data.code === 0){
    message.info(activeRow.value?"编辑成功":"提交成功")
    isUrgent.value = false
    activeRow.value = null
    active.value = false
    refreshList()
  }else{
    const error = result.data.message || '提交失败'
    message.info(error)
  }
}

const refreshList = () => {
  if (taskPanelStatus.value !== 2) {
    taskPanelStatus.value = 2;
  }
  newTask.value = '';
  taskCategorySelector.value = null
  taskTimestamp.value = null
  active.value = false
  if(page.value !== 1){
    page.value = 1
    return
  }
  getTaskList()
}


const getSearchList = () => {
  if((!taskPanelStatus.value && taskPanelStatus.value !== 0) && !taskCategorySelector.value && !taskTimestamp.value){
    return message.warning('请添加筛选项')
  }
  getTaskList()
}

const taskPanelOptions = [
  { value: 0, label: "UNCOMPLETED" },
  { value: 1, label: "COMPLETED" },
  { value: 2, label: "ALL" },
]

const columns = ref([
  { title: "NO.", key: "id" },
  { key: "content", title: "Content", width: "600px", render(row){
    if(Number(row.status)){
      return h(
        'span',
        {style:'color: #ccc;text-decoration:line-through', onClick: () => showClearlyModal(row)},
        { default: () => row.content }
      )
    }else{
      return h(
        'span',
        {style:`color: #333`, onClick: () => showClearlyModal(row)},
        { default: () => row.content }
      )
    }

  } },
  {
    key: "status", title: "Status",
    render(row) {
      return h(
        NTag,
        {
          style: Number(row.status) ? {
            marginRight: "6px",
            color: '#999',
          } : {
            marginRight: "6px",
            color: "#333",
            fontWeight: "bold"
          },
          type: Number(row.status) ? "info" : "warning",
          bordered: false
        },
        {
          default: () => Number(row.status) ? "已完成" : "未完成"
        }
      );
    }
  },
  { key: "category", title: "Category", render(row) {
      return row.category ? row.category : h("span", {style: "color:#999;",}, {default: () => '暂无分类'});
    }
  },
  {key: "zhiding", title: "Ember", render(row){
    return h(
        NTag, {
          type: Number(row.zhiding) ? "warning" : "info",
        }, {
          default: () => Number(row.zhiding) ? "紧急" : "非紧急"
        }
    )
    }},
  { key: "update_time", title: "LastUpdate" },
  {
    key: "", title: "Actions", render(row) {
      return [
        h(
            NButton,
            {
              style: "marginRight: 6px",
              size: 'small',
              onClick: () => editTask(row)
            },
            {default: () => 'Edit'}
        ),
        h(
            NButton,
            {
              size: 'small',
              type: Number(row.status) ? "info" : "primary",
              style: "marginRight: 6px",
              onClick: () => setComplete(row)
            },
            {default: () => Number(row.status) ? 'Restore' : 'Submit'}
        ),
        h(
            NButton,
            {
              size: 'small',
              type: 'error',
              onClick: () => delTask(row)
            },
            {default: () => 'Delete'}
        ),
      ]
    }
  },
])

const showClearlyModal = (row) => {
  rowModal.show = true;
  rowModal.row = row;
}

// 设置完成
const setComplete = async (row) => {
  const data = {
    id: row.id,
    status: Number(!Boolean(Number(row.status)))
  }
  const res = await updateRow(data)
  if(res.data.code === 0){
    Number(row.status) ? message.warning("已重置任务") : message.info("已完成任务")
    page.value = 1
    getTaskList()
  }else{
    const error = res.data.message || '提交失败'
    message.info(error)
  }
}

const editTask = async (row) => {
  activate(row)
}

//删除任务
const delTask = async (row) => {
  dialog.warning({
    title: '警告',
    content: '你确定删除？',
    positiveText: '确定',
    negativeText: '取消',
    draggable: true,
    onPositiveClick: async () => {
      const data = {
        id: row.id,
        del: 1
      }
      const res = await updateRow(data)
      if(res.data.code === 0){
        message.info("已删除任务")
        page.value = 1
        getTaskList()
      }else{
        const error = res.data.message || '提交失败'
        message.info(error)
      }
    }
  })

}

const updateRow = async (data) => {
  return await axios.post(taskUpdateApiUrl, data, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
}

const generateDailyLog = () => {
  const data = {
    page: 1,
    size: 10,
    completed: 1,
    update_time: taskTimestamp.value ? Math.floor(taskTimestamp.value / 1000) : Math.floor(Date.now()/1000)
  }
  axios.post(taskListApiUrl,data,
  { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).then(res => {
    if(res.data.code === 0){
      let log = ''
      res.data.data.list.forEach((el, idx) => {
        log += `${idx+1}. ${el.content}\n`
      })
      console.log(log)
    }
  })
}


const getTaskList = (cb) => {
  listLoading.value = true
  const data = {
    page: page.value,
    size: pagination.pageSize,
    completed: taskPanelStatus.value === 2 ? null : taskPanelStatus.value,
    category: taskCategorySelector.value,
    update_time: taskTimestamp.value ? Math.floor(taskTimestamp.value / 1000) : null,
  }

  axios.post(
      taskListApiUrl,
      data,
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
  ).then(res => {
    taskList.value = res.data.data.list.map((item, index) => {
      return {
        ...item,
        no: index + 1
      }
  });
    pagination.itemCount = Number(res.data.data.total)
    pagination.pageCount = Math.ceil(pagination.itemCount / pagination.pageSize);
  }).finally(() => {
    listLoading.value = false
    cb && cb()
  })
}

const getTaskConf = () => {
  axios.post(taskCategoryUrl).then(res => {
    if(res.data.data){
      categoryOptions.value = res.data.data.map(item => {
        return {
          label: item.name,
          value: item.id
        }
      });
    }
  })
}

watch(page, () => {
  getTaskList()
}, {immediate: false})

onMounted(() => {
  getTaskList()
  getTaskConf()
})
</script>

<style>
li{
  border-bottom: 1px solid #eee;
}
span.label_tk{
  display: inline-block;
  width: 100px;
  height: 30px;
  line-height: 30px;
  text-overflow: ellipsis;
  padding-left: 18px;
  overflow: hidden;
  color: #282828;
  font-weight: 700;
  background-color: #eee;
  font-size: 14px;
}
.cnt{
  display: block;
  text-indent:2em;
}
span.cnt.emmer{
  color:#FF0000;
  font-weight: 700;
}
</style>
